function [M,SD] = wmean(x,sdx)
%WMEAN - weighted mean
%
%       [M,SD] = WMEAN(X,SDX)
%
% For a vector X whose uncertainty vector is SDX, M is the weighted mean
% of X with weigth vectors 1./SDX^2. 
% For matrices, M and SD are row vectors containing the weighted mean 
% values and the corresponding standard deviations for each column.  
% For N-D arrays, M and SD are related to the elements along the first 
% non-singleton dimension of X.
%
% If SDX is undefined or is empty, it is simpy M = MEAN(X) and SD = STD(X).
% The same if one or more elements of sdx ane zero. 

% G. Teza, 2012.

if nargin == 1 || isempty(sdx)
    M = mean(x); SD = stx(x);
    return
end

w = 1./(sdx.^2);
I = find(isinf(w),1,'first');
if ~isempty(I)
    M = mean(x); SD = stx(x);
    return
end

deninv = 1./sum(w);

M  = sum(x.*w).*deninv;
SD = sqrt(deninv);